#include "stdafx.h"
#include "Texture2D.h"
#include "OpenGlExtensions.h"

//-----------------------------------------------------------------------------
// constructors
//-----------------------------------------------------------------------------
CTexture2D::CTexture2D()
{
}

//-----------------------------------------------------------------------------
// destructors
//-----------------------------------------------------------------------------
CTexture2D::~CTexture2D()
{
}

//-----------------------------------------------------------------------------
// functions
//-----------------------------------------------------------------------------

void CTexture2D::Generate()
{
	if (m_nID) Destroy();
	glGenTextures(1, &m_nID);
	Bind();
}

void CTexture2D::Destroy()
{
	if (m_nID != 0)
	{
		glBindTexture(GL_TEXTURE_2D, m_nID);
		glDeleteTextures(1, &m_nID);
		m_nID = 0;
	}
}

void CTexture2D::CreateTextureFromImage(CImageTGA &Image)
{
	if (Image.m_pImageData != 0)
	{
		Generate();

		switch (Image.m_pTGAFileHeader->Image.PixelDepth)
		{
			case 8:
				m_nInternalFormat = GL_LUMINANCE;
				m_nPixelFormat = GL_LUMINANCE;
				break;
			case 24:
				m_nInternalFormat = GL_RGB;
				m_nPixelFormat = GL_RGB;
				break;
			case 32:
				m_nInternalFormat = GL_RGBA;
				m_nPixelFormat = GL_RGBA;
				break;
			default:
				break;
		}

		Bind();
		glTexImage2D(GL_TEXTURE_2D,
					 0,
					 m_nInternalFormat,
					 Image.m_pTGAFileHeader->Image.Width,
					 Image.m_pTGAFileHeader->Image.Height,
					 0,
					 m_nPixelFormat,
					 GL_UNSIGNED_BYTE,
					 Image.m_pImageData);
	}
}

//-----------------------------------------------------------------------------

void CTexture2D::Bind()
{
	if (m_nID == 0)
	{
		glDisable(GL_TEXTURE_2D);
	}
	else
	{
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, m_nID);
	}
}

//-------------------------------------------------------------------------
// tool functions
//-------------------------------------------------------------------------

void SetFilters(unsigned int min_filter, unsigned int mag_filter)
{
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);
}

//-----------------------------------------------------------------------------

void SetWrap(unsigned int s_wrap, unsigned int t_wrap)
{
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, s_wrap);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, t_wrap);
}

//-----------------------------------------------------------------------------

void SetEnvironmentMode(unsigned int blend_mode)
{
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, blend_mode);
}
